import {defineStore} from 'pinia'
import request from '@/utils/request'
import {topCategory} from '../constants'
import { ApiRes, CategoryItem, SubCategory, TopCategory } from '@/types/data'
const defaultCategory = topCategory.map((item) => {
    return {
      name: item,
    }
  })
export default defineStore('category',{
    state() {
        return {
            list:defaultCategory as CategoryItem[],
            topCategory:{} as TopCategory,
            subCategory:{} as SubCategory
        }
    },
    actions:{
        // 发请求,获取数据
     async getAllcategory() {
     const res=await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
     console.log(res.data)
     res.data.result.forEach((item) => {
         item.open = false
       })
      this.list=res.data.result
      },
      show(id: string) {
        // 找到对应 id 的元素, 将其状态改为 true
        const item = this.list.find(item => item.id === id)
        // if (item) {
        //   item.open = true
        // }
        // 优雅的处理方法
        // item && (item.open = true)
        // 暴力处理法: 非空断言, 我断定你一定有 open
        item!.open = true
      },
      hide(id: string) {
        // 找到对应 id 的元素, 将其状态改为 true
        const item = this.list.find(item => item.id === id)
        item!.open = false
      },
      async getTopCategory(id: string) {
        const res = await request.get<ApiRes<TopCategory>>('/category', {
          params: {
            id
          }
        })
        // console.log(res)
        this.topCategory = res.data.result
      },
      async getSubFilter(id: string) {
        const res = await request.get<ApiRes<SubCategory>>(
          '/category/sub/filter',
          {
            params: {
              id,
            },
          }
        )
        console.log(res);
        this.subCategory = res.data.result
      },
    
    }
})
